#pragma once
#include "Task.h"
#include <vector>
#include <mutex>
#include <atomic>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <ctime>
#include <QObject>

class TaskManager : public QObject {
    Q_OBJECT
public:
    TaskManager(QObject* parent = nullptr): QObject(parent){}
    bool addTask(Task& task);
    bool removeTask(int taskId);
    std::vector<Task> getTasksForDay(std::time_t day) const;
    std::vector<Task> getTasksForMonth(std::time_t month) const;
    void checkReminders();
    
    void saveTasks(const std::string& username);
    void loadTasks(const std::string& username, bool preserveExisting = false);
    std::vector<Task> getAllTasks() const;
    
    const std::vector<Task>& getTasks() const { return tasks; }
    Task getTask(int taskId) const;
    int getNextId() {
        //std::lock_guard<std::mutex> lock(tasksMutex);
        return nextId++;
    }
    bool taskExists(const std::string& name, std::time_t startTime) const;

signals:
    void reminderTriggered(const QString& message,int priority); //用于在gui界面中激发提醒
    
private:
    std::vector<Task> tasks;
    mutable std::mutex tasksMutex; // 任务互斥锁
    // 保证多线程环境下对 tasks 向量和其他共享资源的并发访问
    // mutable保证在const限定条件下可以修改互斥锁状态
    std::atomic<int> nextId{1};// 原子变量，无需加锁即可保证多线程下不会出现数据竞争
    std::string current_user;
    
    std::time_t getStartOfDay(std::time_t time) const;
};
